from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from preceda_global import *
from preceda_messages import *
from preceda_menus import *
from preceda_fields import *
import unittest, time, re, csv, logging, datetime

class checkbrowser:
    # =========================== Start: Check Browser ===========================
    # Created by: Giovanni Minoza
    # Date Created: March 06, 2013
    # Date Modified: August 07, 2013
    # Purpose: Select browser and trap errors
    # =========================== Start: Check Browser ===========================
    try:
        if int(globalini.browsers)==0:
            globalflag.chb2v=webdriver.Ie()
            globalflag.chbv=True
        elif int(globalini.browsers)==1:
            globalflag.chb2v=webdriver.Chrome()
            globalflag.chbv=True
        elif int(globalini.browsers)==2:
            globalflag.chb2v=webdriver.Firefox()
            globalflag.chbv=True
        else:
            globalflag.chbv=False
            globalflag.chb2v=webdriver.Ie()
    except:
        globalflag.chbv=False
        globalflag.chb2v=webdriver.Ie()
    # =========================== End: Check Browser ===========================

def writelogs(self,gname,gpath,gtxt):
    # =========================== Start: Save to CSV file ===========================
    # Created by: Giovanni Minoza
    # Date Created: March 05, 2013
    # Date Modified: August 07, 2013
    # Purpose: To enable logging through CSV file
    # =========================== Start: Save to CSV file ===========================
    if globalini.writetocsv==1:
        c = csv.writer(open(gpath+gname+MsgClass.msg20,"a"))
        c.writerow([gtxt])
    # =========================== End: Save to CSV file ===========================

class readrequirements:
    # =========================== Start: Get Initial Data ===========================
    # Created by: Giovanni Minoza
    # Date Created: March 06, 2013
    # Date Modified: August 07, 2013
    # Purpose: Initial extraction of data requirements from CSV file
    # =========================== Start: Get Initial Data ===========================
    def __init__(self):
        global numberofexecution, browser, username, password, client, country
        gtmp=[]
        tmp=readrequirements

        try:
            # there is a problem when login csv file is hard coded
            cr=csv.reader(open(globalini.csvscripts+"preceda_login"+MsgClass.msg25,"rb"))
            for row in cr:
                tmp.tmp=str(row)
                tmp.tmp=tmp.tmp.replace("['","")
                tmp.tmp=tmp.tmp.replace("']","")
                gtmp.append(tmp.tmp)
                tmpflag=True
        except:            
            startwrite=writelogs(self,globalini.joblog,globalini.csvpath,MsgClass.msg11)
            tmpflag=False

        tmp.numberofexecution=gtmp[0]
        tmp.browser=gtmp[1]
        globalflag.precedacountry=gtmp[2]
        tmp.username=gtmp[3]
        tmp.password=gtmp[4]
        tmp.client=gtmp[5]
        globalflag.precedaversion=gtmp[6]
        
        globalflag.flagtocontinue=tmpflag
    # =========================== End: Get Initial Data ===========================

class readtestsuite:
    # =========================== Start: Get Test Suite ===========================
    # Created by: Giovanni Minoza
    # Date Created: August 29, 2013
    # Purpose: Get test suite contents
    # =========================== Start: Get Test Suite ===========================
    def __init__(self,gname):
        try:
            tmp=readtestsuite
            cr=csv.reader(open(str(gname)+MsgClass.msg25,"rb"))
            for row in cr:
                tmp.tmp=str(row)+'.csv'
                tmp.tmp=tmp.tmp.replace("['","")
                tmp.tmp=tmp.tmp.replace("']","")
                if tmp.tmp[0:1]=="#":
                    continue
                try:
                    with open(globalini.csvscripts+tmp.tmp): pass
                    tmpflag=True
                except IOError:
                    tmpflag=False
                    # Something is wrong in this part... Investigate...
                    writelogs(self,globalini.joblog,globalini.csvpath,MsgClass.msg27)
                    break
        except:            
            writelogs(self,globalini.joblog,globalini.csvpath,MsgClass.msg26)
            tmpflag=False

        globalflag.flagtocontinue=tmpflag
    # =========================== End: Get Test Suite ===========================

class runtestsuite:
    # =========================== Start: Get Test Suite ===========================
    # Created by: Giovanni Minoza
    # Date Created: September 03, 2013
    # Purpose: Run all test cases
    # =========================== Start: Get Test Suite ===========================
    def __init__(self,gname):
        self.runthetestnew(gname)

    def runthetestnew(self,gname):
        driver=globalflag.chb2v
        tmpflag=True
        globalflag.tsdr=""
        tmp=readtestsuite
        gtmp=readtestsuite
        cr=csv.reader(open(str(gname)+MsgClass.msg25,"rb"))
        gstring=""
        for row in cr:
            tmp.tmp=str(row)+'.csv'
            tmp.tmp=tmp.tmp.replace("['","")
            tmp.tmp=tmp.tmp.replace("']","")

            if tmp.tmp[0:1]=="#":
                continue

            gtmp.gtmp=""
            gstring=""

            if tmp.tmp.find("login")==-1:
                try:
                    if tmp.tmp.find("screen")!=-1:
                        crv=csv.reader(open(globalini.csvscripts+tmp.tmp,"rb"))
                        globalflag.tsdr=""
                    else:
                        crv=csv.reader(open(globalini.csvscripts+globalflag.tsdr+tmp.tmp,"rb"))
                except:
                    globalflag.flagtocontinue=5
                    break

                for row in crv:
                    gtmp.gtmp=str(row)
                    gtmp.gtmp=gtmp.gtmp.replace("['","")
                    gtmp.gtmp=gtmp.gtmp.replace("']","")
                    if gtmp.gtmp[0:1]=="#":
                        continue
                    #print "   level 2-"+gtmp.gtmp

                    if gstring.find("Screen")!=-1:
                        globalflag.precedaactivity=gstring.replace("Screen;","")
                        mainmenu(gtmp.gtmp)
                        if globalflag.flagtocontinue==False:
                            tmpflag=False
                            break
                        continue

                    if globalflag.flagtocontinue<>True:
                        break

                    #if self.checkerror()==True:
                    #    tmpflag=False
                    #    break

                    if gtmp.gtmp=="Search All":
                        a1=datetime.datetime.now()
                        driver.find_element_by_xpath("//div[contains(@class, \"x-trigger-index-0\")]").click()
                        if driver.find_element_by_id("qsRecordCount").text=="No records found":
                            print "     * No records found"
                            globalflag.flagtocontinue=7
                            tmpflag=False
                        else:
                            print "     * "+driver.find_element_by_id("qsRecordCount").text

                        b1=datetime.datetime.now()
                        c=b1-a1
                        print "  "+gtmp.gtmp+" action: "+str(c)
                    elif gtmp.gtmp.find("New")==0:
                        a1=datetime.datetime.now()
                        gettoolbarmenu("New")
                        b1=datetime.datetime.now()
                        c=b1-a1
                        if gtmp.gtmp.find("New:")==0:
                            htmp=""
                            htmp=gtmp.gtmp.replace("New:","")
                            time.sleep(1)
                            getfields(globalflag.precedacountry,globalflag.precedaactivity,htmp)
                            print "  Fill action: "+str(c)
                        else:
                            print "  "+gtmp.gtmp+" action: "+str(c)
                    elif gtmp.gtmp.find("Refresh")==0:
                        a1=datetime.datetime.now()
                        gettoolbarmenu("Refresh")
                        b1=datetime.datetime.now()
                        c=b1-a1
                        if gtmp.gtmp.find(":")==-1:
                            print "  "+gtmp.gtmp+" action: "+str(c)
                        elif gtmp.gtmp.find(":No")==-1:
                            driver.find_element_by_xpath("//div[contains(@id, \"dialogBtn_YES\")]/em/button[contains(@class,\"x-btn-center\")]").click()
                            print "  Refresh->Save action: "+str(c)
                        else:
                            driver.find_element_by_xpath("//div[contains(@id, \"dialogBtn_No\")]/em/button[contains(@class,\"x-btn-center\")]").click()
                            print "  Refresh->No Save action: "+str(c)

                        time.sleep(1)
                                
                        giantmp=driver.find_element_by_id("statusMessage").text
                        if giantmp.find("has")==-1:
                            globalflag.flagtocontinue=8
                            tmpflag=False
                            self.screenout(globalflag.precedaactivity)
                            time.sleep(1)
                            break
                        else:
                            print "     * "+giantmp
                    elif gtmp.gtmp.find("Save")==0:
                        a1=datetime.datetime.now()
                        gettoolbarmenu("Save")
                        b1=datetime.datetime.now()
                        c=b1-a1
                        print "  "+gtmp.gtmp+" action: "+str(c)
                        time.sleep(1)
                        giantmp=driver.find_element_by_id("statusMessage").text
                        if giantmp.find("information")==-1:
                            if globalflag.precedaversion=="12.1.4":
                                tmppath="//div[contains(@class, \"x-box-inner\")]/div[contains(@class, \"x-component\")]/div[contains(@class, \"essmessage\")]"
                            else:
                                tmppath="//div[contains(@class, \"x-box-inner\")]/div/div[contains(@class, \"x-component\")]/div[contains(@class, \"essmessage\")]"
                            for x in driver.find_elements_by_xpath(tmppath):
                                print "     * "+x.text
                            globalflag.flagtocontinue=6
                            tmpflag=False                                        
                            self.screenout(globalflag.precedaactivity)
                            time.sleep(1)
                            break
                        else:
                            print "     * "+giantmp
                    elif gtmp.gtmp.find("Search")==0:
                        a1=datetime.datetime.now()
                        if globalflag.precedaversion=="12.1.4": 
                            tmppath="//div[contains(@id,\"searchField\")]/div/input"
                        else:
                            tmppath="//td[contains(@id,\"searchField-inputCell\")]/input"
                        htmp=""
                        htmp=gtmp.gtmp.replace("Search:","")
                        driver.find_element_by_xpath(tmppath).send_keys(htmp)
                        driver.find_element_by_xpath("//div[contains(@class, \"x-trigger-index-0\")]").click()
                        b1=datetime.datetime.now()
                        c=b1-a1
                        print "  "+gtmp.gtmp+" action: "+str(c)
                        time.sleep(1)
                        if driver.find_element_by_id("qsRecordCount").text=="No records found":
                            print "     * No records found"
                            globalflag.flagtocontinue=7
                            tmpflag=False
                            time.sleep(1)
                            break
                        else:
                            print "     * "+driver.find_element_by_id("qsRecordCount").text
                    elif gtmp.gtmp.find("Delete")==0:
                        a1=datetime.datetime.now()
                        gettoolbarmenu("Delete")
                        b1=datetime.datetime.now()
                        c=b1-a1
                        if gtmp.gtmp.find(":")==-1:
                            print "  "+gtmp.gtmp+" action: "+str(c)
                            print "     * Record not deleted"
                        elif gtmp.gtmp.find(":No")==-1:
                            driver.find_element_by_xpath("//div[contains(@id, \"dialogBtn_YES\")]/em/button[contains(@class,\"x-btn-center\")]").click()
                            print "  Delete->Yes action: "+str(c)
                            time.sleep(1)
                            giantmp=driver.find_element_by_id("statusMessage").text
                            if giantmp.find("delete")==-1:
                                globalflag.flagtocontinue=8
                                tmpflag=False
                                self.screenout(globalflag.precedaactivity)
                                time.sleep(1)
                                break
                            else:
                                print "     * "+giantmp
                        else:
                            driver.find_element_by_xpath("//div[contains(@id, \"dialogBtn_No\")]/em/button[contains(@class,\"x-btn-center\")]").click()
                            print "  Delete->No action: "+str(c)
                            print "     * Record not deleted"
                    elif gtmp.gtmp.find("Modify")==0:
                        a1=datetime.datetime.now()
                        if gtmp.gtmp.find("Modify:")==0:
                            htmp=""
                            htmp=gtmp.gtmp.replace("Modify:","")
                            getfields(globalflag.precedacountry,globalflag.precedaactivity,htmp)
                            time.sleep(1)
                        b1=datetime.datetime.now()
                        c=b1-a1
                        print "  Modify action: "+str(c)




                        

                    if globalflag.flagtocontinue!=True:
                        tmpflag=False
                    elif self.checkerror()==True:
                        tmpflag=False
                        break


                    
                    #if gstring.find("New")==-1:
                    #    gettoolbarmenu("New")
                    #    if globalflag.flagtocontinue!=True:
                    #        tmpflag=False
                    #    else:
                    #        if self.checkerror()==True:
                    #            tmpflag=False
                    #            break
                    #elif gstring.find("Delete")==-1:
                    #    gettoolbarmenu("Delete")
                    #elif gstring.find("Refresh")==-1:
                    #    gettoolbarmenu("Refresh")
                    #elif gstring.find("Modify")==-1:
                    #    print ""
                    #elif gstring.find("Save")==-1:
                    #    print ""
                    #elif gstring=="Search All":
                    #    driver.find_element_by_xpath("//div[contains(@class, \"x-trigger-index-0\")]").click()
                    #    if driver.find_element_by_id("qsRecordCount").text=="No records found":
                    #        print "     * No records found"
                    #        globalflag.flagtocontinue=7
                    #        tmpflag=False
                    #    else:
                    #        print "     * "+driver.find_element_by_id("qsRecordCount").text
                    #elif gstring.find("Search")==-1:
                    #    print ""


                    gstring=gtmp.gtmp

                if tmpflag!=True:
                    break

    def checkifvalidaction(self,defaction,testaction):
        if defaction==1:
            if testaction=="New":
                return True
            elif testaction=="Save":
                return True
            elif testaction=="Delete":
                return True
            elif testaction=="Refresh":
                return True
            elif testaction=="Clone":
                return True
            else:
                return False
        else:
            return False

    def screenout(self,gfile):
        # =========================== Start: Screen Capture ===========================
        # Created by: Giovanni Minoza
        # Date Created: February 26, 2013
        # Purpose: Screenshot and save to folder as image file
        # =========================== Start: Screen Capture ===========================
        driver=globalflag.chb2v
        try: driver.save_screenshot(str(globalini.screenoutput)+gfile+"-"+datetime.datetime.now().time().strftime("%H%M%S")+".png")
        except: print "     * Unable to capture screen"
        #print "   Temporary screenshot"
        # =========================== End: Screen Capture ===========================

    def checkerror(self):
        #driver=globalflag.chb2v
        #try:
        #    print "     *"+driver.find_element_by_xpath("//div[contains(@class,\"x-window\")]/div[contains(@class,\"x-window-body\")]/span").text
        #    driver.find_element_by_xpath("//div[contains(@id,\"dialogBtn_LOG\")]/em/button").click()
        #    globalflag.flagtocontinue=10
        #    return True
        #except:
        #    return False
        #print "   Temporary script error check"
        pass
        # =========================== End: Get Test Suite ===========================

class screenout:
    # =========================== Start: Screen Capture ===========================
    # Created by: Giovanni Minoza
    # Date Created: February 26, 2013
    # Date Modified: August 08, 2013
    # Purpose: Screenshot and save to folder as image file
    # =========================== Start: Screen Capture ===========================
    #def __init__(self,gscreen,gfile):
    #    self.save_screenshot(str(screenoutput)+str(gfile)+MsgClass.msg21)
    pass
    # =========================== End: Screen Capture ===========================

class checkrequirements:
    # =========================== Start: Check File ===========================
    # Created by: Giovanni Minoza
    # Date Created: March 06, 2013
    # Date Modified: August 08, 2013
    # Purpose: Check first if CSV file is present
    # =========================== Start: Check File ===========================
    def __init__(self,gname,gpath):
        try:
            cr=csv.reader(open(gpath+str(gname)+MsgClass.msg19,"rb"))
            chkrq=True
        except: chkrq=False
    # =========================== End: Check File ===========================

class gettoolbarmenu:
    # =========================== Start: Action Buttons ===========================
    # Created by: Giovanni Minoza
    # Date Created: March 14, 2013
    # Date Modified: June 11, 2013; August 14, 2013
    # Purpose: Select main tool bar button
    # =========================== Start: Action Buttons ===========================
    def __init__(self,screenaction):
        driver=globalflag.chb2v
        if globalflag.precedaversion=="12.1.4":
            gtmpdp="//div[contains(@class, \"x-box-inner\")]/div[contains(@class, \"x-btn\")]"
            gtmpstr="//div[contains(@id, \"mainToolbar\")]/div[contains(@class, \"x-box-inner\")]/div[contains(@class, \"x-btn\")]/span[contains(text(), \""+screenaction+"\")]"
        else:
            gtmpdp="//div[contains(@class, \"x-box-inner\")]/div/div[contains(@class, \"x-btn\")]"
            gtmpstr="//div[contains(@id, \"mainToolbar\")]/div[contains(@class, \"x-box-inner\")]/div/div[contains(@class, \"x-btn\")]/em/button/span/span[contains(text(), \""+screenaction+"\")]"
        #print driver.find_element_by_xpath(gtmpstr).get_attribute("class")
        #globalflag.flagtocontinue=3
        #try:
        #    driver.find_element_by_xpath(gtmpstr).get_attribute("class")
            #driver.find_element_by_xpath(gtmpstr).click()
        #except:
        #    globalflag.flagtocontinue=3
        for i in driver.find_elements_by_xpath(gtmpdp):
            if i.text<>"":
                #print "   "+i.text
                mword="x-btn-disabled"
                msentence1=i.get_attribute("class")
                msentence=msentence1.split()
                if i.text==screenaction:
                    if mword in msentence:
                        globalflag.flagtocontinue=3
                        #print i.text+"-Disabled"
                    else:
                        driver.find_element_by_xpath(gtmpstr).click()
                        #print i.text+"-Enabled"
                    break
    # =========================== End: Action Buttons ===========================
